package cn.codeforfun.interceptor.adapter;

import cn.codeforfun.consts.SessionConsts;
import cn.codeforfun.interceptor.LoginInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/2/14 0014.
 */
public class LoginInterceptorAdaptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (o instanceof HandlerMethod) {//java.lang.ClassCastException: org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
            HandlerMethod handlerMethod = (HandlerMethod) o;
            Method method = handlerMethod.getMethod();

            //获取方法级拦截器注解
            LoginInterceptor annotation = method.getAnnotation(LoginInterceptor.class);
            //获取类级别拦截器注解
            LoginInterceptor annotation1 = ((HandlerMethod) o).getBean().getClass().getAnnotation(LoginInterceptor.class);
            if (annotation != null || annotation1 != null) {
                HttpSession session = request.getSession();
                if (session.getAttribute(SessionConsts.USER) == null) {
                    //不通过
                    response.sendRedirect(request.getContextPath() + "/loginPage");
                    return false;
                }
            }
        }
        // 没有注解通过拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
